<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
    .box{
        width: 300px;
        height: 300px;
        background: tomato;
        position: absolute;
        top: 50px;
        left: 50px;
    }
</style>
<body>
<button class="btn1">前进按钮</button>
<button class="btn2">后退按钮</button>
<div class="box">

</div>
<script>
    var box = document.querySelector('.box');

    /*var time = setInterval(function () {
        if (box.offsetLeft <= 500) {
            box.style.left = box.offsetLeft + 5 + 'px';
            box.innerHTML = '拜拜了您！';
        }else if (box.offsetTop <= 500) {
            box.style.top = box.offsetTop + 5 +'px';
        } else if (box.offsetLeft <= 1000) {
            box.style.left = box.offsetLeft + 5 + 'px';
        }
    },50);*/
    function animate(obj,target,callback) {      //封装成函数可以多次调用
        clearInterval(obj.tiems);   /*每次点击按钮时都会清除一次动画防止出现BUG*/
        obj.tiems = setInterval(function () {
            var temp = (target - obj.offsetLeft) / 10;  /*缓动动画 利用（目标值 - 现在的位置） / 10*/
            temp = temp > 0 ? Math.ceil(temp) : Math.floor(temp);
            if (obj.offsetLeft == target) {
                clearInterval(obj.tiems);
                if (callback) {
                    callback();   //结束的时候判断是否有回调函数有的话就会执行
                }
            }
            obj.style.left = obj.offsetLeft + temp + 'px';
        },15)
    }
    var btn1 = document.querySelector('.btn1');
    var btn2 = document.querySelector('.btn2');
    btn1.addEventListener('click',function () {
        animate(box,500,function () {
            box.style.background = '#333';  //回调函数
        })
    });
    btn2.addEventListener('click',function () {
        animate(box,50)
    });
</script>
</body>
</html>